﻿/// <reference path="../typings/jquery/jquery.d.ts" />
/// <reference path="../typings/jquery/jquery.easyui.d.ts" />
/// <reference path="Common.ts" />

/**页面处理*/
class JsPage {    

    // #region private field

    /**
     * jquery easyui datagrid control
     */
    public _datagrid: any;
     /**
     * jquery easyui dialog control
     */
    private _dialog: any;
     /**
     * jquery easyui form control
     */
    private _form: any;
     /**
     * jquery easyui menu control
     */
    private _cmenu: any;
    /**
     * 请求地址
     */
    private _url: string;
    //#endregion 

           
    // #region public property

    PageSize: number = 10;
    PageNumber: number = 1;

    //#endregion 
    
    // #region  construct dispose

    /**
     * 构造函数
     */
    constructor() {

    }

    /**
     * 析构函数
     */
    destroy() {
    }    
    //#endregion 

    // #region  datagrid

     /**
     * 设置列表控件
     */
    public setDataGrid = (datagrid: any, onclick: any = null): JsPage=>
    {
        this._datagrid = datagrid;
        if (onclick == null) onclick = this.OnClickRow;

        this._datagrid.datagrid({
            pageSize: this.PageSize,
            pageNumber: this.PageNumber,
            onClickRow: onclick,
            loader: this.Loader,
            onHeaderContextMenu: this.OnHeaderContextMenu
        });

        return this;
    }

    public loadDataGrid=(url: string)=> {
        this._url = url;
        this._datagrid.datagrid({ url: url, pageNumber: 1 });
    }
        
    /**
    * datagrid 单击选中
    **/
    private OnClickRow=(index)=>
    {
        var grid = this._datagrid;
        if (!grid) return;
        var selIndex = grid.data().datagrid['selectRowIndex'];

        if (selIndex != index) {
            grid.datagrid('selectRow', index);
            selIndex = index;
        }
        else {
            grid.datagrid('selectRow', -1);
            selIndex = null;
        }

        grid.data().datagrid['selectRowIndex'] = selIndex;
    }

    /**
    * datagrid 强制刷新
    **/
    private Loader =(param, success, error)=> {
        var opts = this._datagrid.datagrid("options");
        if (!opts.url) {
            return false;
        }

        var ajaxCached= this._datagrid.data("ajaxcached");//不使用ajax缓存

        $.ajax({
            type: opts.method,
            url: opts.url,
            cache: ajaxCached,
            data: param,
            dataType: "json",
            success: function (data) {
                success(data);
            },
            error: function () {
                error.apply(this, arguments);
            }
        });
    }

    /**
    * datagrid 上下文菜单
    **/
    private OnHeaderContextMenu = (e, field)=> {
        e.preventDefault();
        if (!this._cmenu) {
            this.createColumnMenu();
        }
        this._cmenu.menu('show', {
            left: e.pageX,
            top: e.pageY
        });
    }
    
    /**
    * datagrid 创建菜单
    **/
    private createColumnMenu = () => {
        this._cmenu = $('<div/>').appendTo('body');
        this._cmenu.menu({
            onClick: (item)=> {
                if (item.iconCls == 'icon-ok') {
                    this._datagrid.datagrid('hideColumn', item.name);
                    this._cmenu.menu('setIcon', {
                        target: item.target,
                        iconCls: 'icon-empty'
                    });
                } else {
                    this._datagrid.datagrid('showColumn', item.name);
                    this._cmenu.menu('setIcon', {
                        target: item.target,
                        iconCls: 'icon-ok'
                    });
                }
            }
        });
        var fields = this._datagrid.datagrid('getColumnFields');
        for (var i = 0; i < fields.length; i++) {
            var field = fields[i];
            var col = this._datagrid.datagrid('getColumnOption', field);
            this._cmenu.menu('appendItem', {
                text: col.title,
                name: field,
                iconCls: 'icon-ok'
            });
        }
    }    
    //#endregion 

    // #region  Dialog
    /**
     * 设置对话框
     */
    public setDialog=(dialog: any): JsPage=> {
        this._dialog = dialog;

        return this;
    }
    /**
     * 关闭对话框
     */
    public closeDialog=()=> {
        if (this._dialog)
        {
            this._dialog.dialog('close');
        }
    }
    //#endregion

    // #region  Form
    /**
     * 设置表单
     */
    public setForm=(form: any): JsPage=> {
        this._form = form;

        return this;
    }

    /**
     * 设置对话框
     */
    public sumbitForm=(fm)=> {
        $.messager.progress({
            title: '请等待',
            msg: '加载数据中...'
        });

        if (!fm) fm = this._form;

        var result = fm.form('enableValidation').form('validate');
        if (result) {
            fm.ajaxSubmit({
                complete: function () {
                    $.messager.progress('close');
                },
                success: (responseText) => {
                    if (responseText != undefined && responseText.length >= 1) {
                        $.messager.alert('错误提示', responseText, "error");
                    }
                    else {
                        if (this._datagrid) {
                            this._datagrid.data().datagrid.selectRowIndex = null;
                            this._datagrid.datagrid('reload');
                        }
                        if (this._dialog)
                            this._dialog.dialog('close');
                    }

                },
                error: Common.ShowError
            });
        }
        else {
            $.messager.progress('close');
            $.messager.alert('验证失败', '请修改填写错误的数据,红色框框的数据代表错误!');
        }
    }
    //#endregion
        
    // #region  eventHandler

    public AddAction = (args: Common.Action)=> {
        if (args) {
            args();
        }
        if (this._form)
            this._form.form('clear');
        if (this._dialog)
            this._dialog.dialog('open');
    }

    public EditAction = (args: Common.Action) => {
        var row = this._datagrid.datagrid('getSelected');
        if (!row) {

            $.messager.alert('消息提示', '编辑数据时，请选择一项!', 'warning');
            return;
        }

        if (args) {
            args();
        }

        if (this._form)
            this._form.form('load', row);
        if (this._dialog)
            this._dialog.dialog('open');
    }

    public RemoveAction = (url:string,args: Common.Action) => {
        var row = this._datagrid.datagrid('getSelected');
        if (!row) {

            $.messager.alert('消息提示', '删除数据时，请选择一项!', 'warning');
            return;
        }

        if (args) {
            args();
        }

        if (!url) url = this._url;

        $.messager.confirm('删除提示', '你确定需要删除?', (r)=> {
            if (r) {
                $.ajax({
                    type: "Delete",
                    url: url,
                    data: row,
                    success: () => {
                        if (this._datagrid) {
                            this._datagrid.data().datagrid.selectRowIndex = null;
                            this._datagrid.datagrid("getPager").pagination('select', 1);
                        }
                        if (this._dialog) this._dialog.dialog('close');
                    },
                    error: Common.ShowError
                });
            }
        });  

    }

    public SearchAction = (pair: Common.KeyValuePair<string, string> [], url: string, args: Common.Action) => {
        if (args) {
            args();
        }

        if (!url) url = this._url;

        var urlParam:string[]=[];
        pair.forEach((value, index, array) => {
            if (value.value != "" && value.value != "0")
            {
                urlParam.push(value.key + "=" +encodeURI(value.value));
            }

        });

        if (urlParam.length ==1)
        {
            url += "?" + urlParam;
        }
        else if (urlParam.length > 1)
        {
            url += "?" + urlParam.join("&");
        }

        var options = { url: url, pageNumber: 1 }
        this._datagrid.datagrid(options);
    }
    //#endregion
    
}
